package org.easySpace.common.handler;

import org.easySpace.common.enums.ErrorEnum;
import lombok.extern.slf4j.Slf4j;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.sql.SQLIntegrityConstraintViolationException;

/**
 * @author lzh@aginome.com
 * @description 全局异常捕获，用于处理程序中可能出现的异常，再返回给前端规定好的提示信息
 * @date 2022-06-02 17:30
 */


@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {


    /**
     * 自定义异常 -- 外键不存在异常
     *
     * @param e
     * @return
     */
    @ExceptionHandler(value = DataIntegrityViolationException.class)
    public ResponseEntity sqlException(SQLIntegrityConstraintViolationException e) {
        log.error(e.getMessage(), e);
        return new ResponseEntity(ResponseDto.otherError(ErrorEnum.NOT_EXIST_FOREIGN_KEY), HttpStatus.INTERNAL_SERVER_ERROR);
    }

    /**
     * 处理其他异常
     */
    @ExceptionHandler(value = Exception.class)
    public ResponseEntity exceptionHandler(Exception e) {
        log.error(e.getMessage(), e);
        return new ResponseEntity(ResponseDto.errorMessage(ErrorEnum.INTERNAL_SERVER_ERROR, e), HttpStatus.INTERNAL_SERVER_ERROR);
    }

    /**
     * 非法参数异常
     *
     * @param e
     * @return
     */
    @ExceptionHandler(value = IllegalArgumentException.class)
    public ResponseEntity illegalArgumentException(IllegalArgumentException e) {
        log.error(e.getMessage(), e);
        return new ResponseEntity(ResponseDto.errorMessage(ErrorEnum.ILLEGAL_ARGUMENT, e), HttpStatus.INTERNAL_SERVER_ERROR);
    }

}
